//
//  nevarByVC.m
//  lyxluyou
//
//  Created by mmyy on 15/10/17.
//  Copyright (c) 2015年 mmyy. All rights reserved.
//

#import "nevarByVC.h"

#import "NevarByItems.h"

#import "nevarByCell.h"

#import "nevarByxqVC.h"

#import "SearchViewControll.h"

#import "RDVTabBarController.h"

#import "WeatherVC.h"

@interface nevarByVC ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, searchViewDelegate>

@end

@implementation nevarByVC
{
    Map *map;
    UITableView *_tableView;
    NSMutableArray *_dataSource;
    UIScrollView *_headView;
    NSInteger currentPage;
    UISearchController * _searchController;
    int current;
    BOOL isUpdate;
    NSMutableArray *_searchArray;
    CLLocationCoordinate2D coor;
    CLLocationCoordinate2D searCoor;
    BOOL isSearch;
    UIImageView *_bgImage;
    UIButton *_leftBt;
    UIButton *_rightBt;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取当前位置
    map = [Map shareMap];
    [map startLocation];
    currentPage = 10;
    current = 10;
    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor purpleColor];
    
    _dataSource = [NSMutableArray arrayWithCapacity:0];
    
    isUpdate = NO;
    
    isSearch = NO;
    //获取数据
    [self createHeadView];
    
    [self createTableView];
    //创建表格
    [self createNavacation];
    
    [self createloadDataImage];

//    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(coorSuccess) name:@"CoorSuccess" object:nil];
    
}
-(void)createNavacation
{
    _leftBt = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 80, 30)];
    [_leftBt setTitle:@"北京" forState:UIControlStateNormal];
    [_leftBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_leftBt addTarget:self action:@selector(leftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    _leftBt.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithCustomView:_leftBt];
    self.navigationItem.leftBarButtonItem = leftBar;
    self.navigationItem.title = @"附近的景点";
    _rightBt = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [_rightBt setTitle:@"天气" forState:UIControlStateNormal];
    [_rightBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_rightBt addTarget:self action:@selector(leftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    _rightBt.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBt];
}
-(void)leftButtonClick:(UIButton *)sender
{
    if ([sender.currentTitle isEqualToString:@"天气"]) {
        WeatherVC *weather = [[WeatherVC alloc] init];
        weather.currentCity = _leftBt.currentTitle;
        [self.navigationController pushViewController:weather animated:YES];
    }else {
        SearchViewControll *search = [[SearchViewControll alloc] init];
        search.currentCity = sender.currentTitle;
        search.delegate = self;
        [self.navigationController pushViewController:search animated:YES];
    }
}
-(void)searchViewSuccess:(NSString *)searchCity
{
    if ([searchCity length] != 0) {
        [_leftBt setTitle:searchCity forState:UIControlStateNormal];
        [map searchMapWithString:searchCity success:^(NSArray *array) {
            CLPlacemark *placemark = [array firstObject];
            CLLocation *location = placemark.location;
            searCoor = location.coordinate;
            isSearch = YES;
            [self loadData];
        } andFail:^(NSError *error) {
            
        }];
    }

}
-(void)createloadDataImage
{
    _bgImage = [loadImage loadImage];
    _bgImage.frame = CGRectMake((self.view.frame.size.width - 100) / 2.0, (self.view.frame.size.height - 100) / 2, 100, 100);
    [self.view addSubview:_bgImage];
}
-(void)coorSuccess
{
    
    if (coor.latitude == 0 && coor.longitude == 0) {
        coor = [map coor];
        CGFloat latit = coor.latitude;
        CGFloat lon = coor.longitude;
        [self loadData];
        CLLocation *location = [[CLLocation alloc] initWithLatitude:latit longitude:lon];
        [map reverseGeocodeLocation:location success:^(NSArray *array) {
            CLPlacemark *placemark = [array lastObject];
            NSDictionary *addres = [placemark addressDictionary];
            [_leftBt setTitle:[addres objectForKey:@"City"] forState:UIControlStateNormal];
        } andFail:^(NSError *error) {
            NSLog(@"%@", error);
        }];
    }
    
    NSLog(@"%f ---- %f", coor.latitude, coor.longitude);
//    [[NSNotificationCenter description] removeObserver:self forKeyPath:@"CoorSuccess"];
}
-(void)createNavCation
{
    self.navigationItem.title = @"附近旅游";
//    [self createSearchController];
}
-(void)createHeadView
{
    NSArray *name = @[@"景点", @"住宿", @"餐厅", @"娱乐", @"交通"];
    _headView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 65, self.view.frame.size.width - 20, 40)];
    _headView.backgroundColor = [UIColor purpleColor];
    _headView.showsHorizontalScrollIndicator = NO;
    CGFloat appw = (self.view.frame.size.width - 20 - 20) / 4;
    for (int i = 0; i < name.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(5 + i * (appw + 5), 5, appw, 30)];
        button.layer.cornerRadius = 10;
        button.layer.masksToBounds = YES;
        [button setTitle:name[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor clearColor];
        button.tag = 10 + i;
        if (i == 0) {
            button.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        }
        [_headView addSubview:button];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    _headView.contentSize = CGSizeMake(name.count * (5 + appw) , 40);
    [self.view addSubview:_headView];
}
-(void)buttonClick:(UIButton *)sender
{
    for (int i = 0; i < 5; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:i + 10];
        if (button.tag == sender.tag) {
            [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor whiteColor];

        }else {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
        
        }
    }
    currentPage = sender.tag;
    [self loadData];

}
-(void)loadData
{
    _bgImage.hidden = NO;
    NSArray *picCount = @[@11, @10, @5, @13, @15];
    NSString *url = nil;
    if (isSearch) {
        url = [NSString stringWithFormat:nearbyUrl, picCount[currentPage - 10], current, searCoor.latitude, searCoor.longitude];
        
    }else {
        url = [NSString stringWithFormat:nearbyUrl, picCount[currentPage - 10], current, coor.latitude, coor.longitude];
    }
    [Funcation getWithURL:url success:^(id responseObject) {
        _bgImage.hidden = YES;
        if (!isSearch) {
            _dataSource = [NSMutableArray arrayWithCapacity:0];
            [NevarByItems removeAllDataWithCategory:picCount[currentPage - 10]];
        }else _searchArray = [NSMutableArray arrayWithCapacity:0];
        
        NSArray *items = [responseObject objectForKey:@"items"];
        for (NSDictionary *dict in items) {
            
            if (isSearch) {
                NevarByItems *item = [NevarByItems nevarByItemsWithDict:dict isSearch:YES];
                [_searchArray addObject:item];
            }else {
                NevarByItems *item = [NevarByItems nevarByItemsWithDict:dict isSearch:NO];
                [_dataSource addObject:item];
            }
        }
        [_tableView reloadData];
    } andFail:^(id error) {
        _bgImage.hidden = YES;
    }];
    if (!isSearch) {
        NSArray *data = [NevarByItems getDataWithCategory:picCount[currentPage - 10]];
        [_dataSource addObjectsFromArray:data];
        [_tableView reloadData];
    }
    
    
    if (isUpdate) {
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
        isUpdate = NO;
    }

}
-(void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40 + 64, self.view.frame.size.width, self.view.frame.size.height - 40 - 64 - 44) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorColor = [UIColor clearColor];
    _tableView.rowHeight = 100;
    _tableView.backgroundColor = [UIColor purpleColor];
    UISwipeGestureRecognizer *left = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftChange)];
    left.direction = UISwipeGestureRecognizerDirectionLeft;
    [_tableView addGestureRecognizer:left];
    UISwipeGestureRecognizer *right = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightChange)];
    right.direction = UISwipeGestureRecognizerDirectionRight;
    [_tableView addGestureRecognizer:right];
    [self.view addSubview:_tableView];
    __weak UITableView *newTable = _tableView;
    __weak nevarByVC *newSelf = self;
    [_tableView addHeaderWithCallback:^{
        newTable.headerRefreshingText = @"下拉刷新";
        isUpdate = YES;
        [newSelf loadData];
    }];
    [_tableView addFooterWithCallback:^{
        current += 10;
        isUpdate = YES;
        newTable.footerRefreshingText = @"上拉加载更多";
        [newSelf loadData];
    }];

    
}
-(void)rightChange
{
    if (currentPage != 10) {
        currentPage -= 1;
        UIButton *bt = (UIButton *)[_headView viewWithTag:currentPage];
        [self buttonClick:bt];
        [_headView setContentOffset:CGPointMake(0 * (5 + 80), 0)];
        
    }

}
-(void)leftChange
{
    if (currentPage != 14) {
        currentPage += 1;
        UIButton *bt = (UIButton *)[_headView viewWithTag:currentPage];
        [self buttonClick:bt];
        [_headView setContentOffset:CGPointMake(1 * (5 + 80), 0)];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isSearch) {
        return _searchArray.count;
    }
    return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    nevarByCell *cell = [tableView dequeueReusableCellWithIdentifier:@"basis_cell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"nevarByCell" owner:nil options:nil] lastObject];
    }
    NevarByItems *items;
    if (isSearch) {
        items = [_searchArray objectAtIndex:indexPath.row];
    }else {
        items = [_dataSource objectAtIndex:indexPath.row];
    }
    cell.bgImage.backgroundColor = [UIColor orangeColor];
    if (![items.cover_s isKindOfClass:[NSNull class]]) {
        [cell.bgImage setImageWithURL:[NSURL URLWithString:items.cover_s] placeholderImage:[UIImage imageNamed:@"define"]];
    }
    
    cell.name.text = items.name;
    cell.backgroundColor = [UIColor clearColor];
    cell.rating_users.text = [NSString stringWithFormat:@"评论:%@", items.rating_users];
    [cell.star setStarValue:[items.rating floatValue] / 5.0];
    cell.commed.text = items.recommended_reason;
    cell.commed.lineBreakMode = NSLineBreakByWordWrapping;
    cell.commed.numberOfLines = 2;
    cell.commed.adjustsFontSizeToFitWidth = YES;
    if ([items.wish_to_go_count integerValue] == 0) {
        cell.wish_to_go.text = @"大于100km";
    }else cell.wish_to_go.text = [NSString stringWithFormat:@"距离我:%@km",items.wish_to_go_count];
    cell.wish_to_go.adjustsFontSizeToFitWidth = YES;
    cell.visitPeople.text = [NSString stringWithFormat:@"%@人去过",items.visited_count];
    cell.visitPeople.adjustsFontSizeToFitWidth = YES;
    return cell;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NevarByItems *items = nil;
    if (isSearch) {
        items = [_searchArray objectAtIndex:indexPath.row];
    }else {
        items = [_dataSource objectAtIndex:indexPath.row];
    }
    nevarByxqVC *vc = [nevarByxqVC new];
    vc.title = items.name;
    vc.vid = items.vid;
    NSLog(@"%@", vc.vid);
    [self.navigationController pushViewController:vc animated:YES];

}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.rdv_tabBarController setTabBarHidden:NO animated:NO];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.rdv_tabBarController setTabBarHidden:YES animated:NO];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"CoorSuccess"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
